Shader "UI/SequenceAnimation"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _HorizontalFrames ("横向帧数", int) = 4
        _VerticalFrames ("纵向帧数", int) = 1
        _Speed ("播放速度（帧/秒）", Range(0, 60)) = 10
        [Toggle(USE_PIXEL_SNAP)] _PixelSnap ("像素对齐", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "RenderType"="Transparent"
            "Queue"="Transparent"
        }

        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile __ USE_PIXEL_SNAP

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            int _HorizontalFrames;
            int _VerticalFrames;
            float _Speed;

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                // 计算总帧数
                int totalFrames = _HorizontalFrames * _VerticalFrames;
                
                // 计算当前帧索引
                float frame = fmod(_Time.y * _Speed, totalFrames);
                int frameIndex = (int)frame;
                
                // 计算行列索引
                int row = frameIndex / _HorizontalFrames;
                int col = frameIndex % _HorizontalFrames;
                
                // 计算UV偏移
                float2 uv = i.uv;
                uv.x /= _HorizontalFrames;
                uv.y /= _VerticalFrames;
                uv.x += col * (1.0 / _HorizontalFrames);
                uv.y += row * (1.0 / _VerticalFrames);

                return tex2D(_MainTex, uv);
            }
            ENDCG
        }
    }
}